import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import {config} from '../../../shared/smartadmin.config';

declare var $: any;
declare var BMap: any;
declare var BMapLib: any;
declare var echarts: any;
declare var toMapPoint: any;
@Component({
  selector: 'sa-task-manage',
  templateUrl: './task-manage.component.html',
  styleUrls:['./task-manage.css']
})
export class TaskManageComponent implements OnInit {
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	carList:any[] = [];
	companyId:string = '';
	companyList = [];
	deviceId:string = '';//设备ID
	carNumber:string = '';
	startTime:string = '';//开始时间
	endTime:string = '';//结束时间
	btnNum:string = 'all';
	allData:string = '';//数据分类总数
	normalData:string = '';//数据分类正常
	abnormalData:string = '';//数据分类异常
	flag:boolean = false;//记录弹层的显示和隐藏
	isloading:boolean = false;//判断数据是否除以加载中
	activeSelected:string = ''; //row高亮

	mapCantonName:string = '';//行政区域名
	mapCarNumber:string = '';
	mapDeviceId:string = '';
	mapStartTime:string = '';
	mapEndTime:string = '';
	baiduMap:any; //实例化地图对象
	trackData:any[] = [];//轨迹路线数据
	carMoveCanvasLayer:any;//移动折线对应地图添加点的,
	boundaryRegion:any;//行政边界区域构造器
	areaPly:any;//行政边界区域的覆盖图形
	isEnter:boolean = true;//默认选中进入特价区域
	inTimeArr:any[] = [];//存储进入边界的时间,对应outTimeArr离开边界的时间
	outTimeArr:any[] = [];
	inRegionTime:string = '';//进入边界时间
	outRegionTime:string = '';//进入边界后离开时间
	myChart:any;//实例化折线图对象
	chartOption:any;//折线图配置
	xAxisData:any[] = [];//折线图X轴时间数据
	yAxisWeight:any[] = [];//重量折线数据
	yAxisSpeed:any[] = [];//速度折线数据
	//基本信息
	basInformation:any[] = [];
	timeOut:any;
	constructor(private jsonApiService: JsonApiService) {}

	ngOnInit() {
		this.initBaiduMap();//初始化地图
		this.boundaryRegion = new BMap.Boundary();//初始化一个行政边界区域构造器
		this.initDate().then(()=>{this.load()});
		this.selectCompany();
	}
	ngOnDestroy(){
		clearTimeout(this.timeOut);
	}
	getTime(date){
		var year = date.getFullYear();
		var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
		var day = date.getDate()  < 10 ? "0" + date.getDate() : date.getDate();
		var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		return year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
	}
	//刷新
	refresh(){
		this.load();
	}
	table_search(){
		this.curPage = 1;
		this.load();
	}
	//数据分类按钮点击事件
	btnClick(type){
		this.btnNum = type;
		this.curPage = 1;
		$('#popPage').animate({'width':0,'opacity':0},150);
		this.flag = false;
		this.load();
	}
	//初始化时间
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true
						}).on("changeDate", function(e){
							var date = e.date;
							var time = that.getTime(date);
							that.startTime=time;
							$("#datetimepicker2").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker2").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true
						}).on("changeDate", function(e){
							var date = e.date;
							var time = that.getTime(date);
							that.endTime=time;
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
//						var date = new Date();
//						$("#datetimepicker2").val(that.getTime(date));//当前时间
//						date.setDate(date.getDate() - 7);//设置前一天
//						$("#datetimepicker1").val(that.getTime(date));
						resolve();
					});
				}
			);
		})

	}
	//初始化车辆
	selectCompany(){
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				var that = this;
		        $("#carNumberSelect2").select2({
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	minimumInputLength : 2,      //最少2个字符，select2才显示查询的内容
			    	ajax: {
			    		url: config.BaseURL+"stats/carListByCarNumber.html",
			    		dataType: 'json',
			    		delay: 50,
			    		method: "POST",
			    		xhrFields: {withCredentials: true},
			    		data: function (params) {
			    		    return {
			    		   	 	"carNumber" :  params.term // search term
			    		    };
			    		},
			    		processResults: function(data, params) {
							var options = new Array();
							// 小于10个数量才判断重复
							if(data.data.length<=10){
								let arr = []
								let sameCar = []
								// 判断相同的车牌号
								for (let index = 0; index < data.data.length; index++) {
									let car = data.data[index];
									if(arr.indexOf(car.carNumber)!=-1){
										sameCar.push(car.carNumber)
									}else{
										arr.push(car.carNumber);
									}
								}
								$(data.data).each(function(index, car) {
									if(sameCar.indexOf(car.carNumber)!=-1){
										options.push({
											id: car.deviceId,
											text: car.carNumber+"["+car.parentName+"]"
										})
									}else{
										options.push({
											id: car.deviceId,
											text: car.carNumber
										})
									}
								});
							}else{
								$(data.data).each(function(index, car) {
									options.push({
										id: car.deviceId,
										text: car.carNumber
									})
								});
							}
							return {
								results: options //获取查询后的结果
							};
						},
			    		cache: true
			         },
			         templateResult: this.formatRepo
			    }).on ("select2:select", function (e) {
		        	  	var data = e.params.data;
						that.deviceId = data.id;
						  if(data.text.indexOf('[') > 0){
							that.carNumber = data.text.split('[')[0];
						} else {
							that.carNumber = data.text;
						}
		       });
			})
	  	})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//清除车辆选中值
	del_carNumber(){
		this.deviceId = '';
		this.carNumber = '';
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberSelect2').val("");
		$("#select2-carNumberSelect2-container").empty();
		$("#select2-carNumberSelect2-container").attr("title","");
		$("#select2-carNumberSelect2-container").prepend(str);
	}
	loadSortData(){
		let reqdata = 'deviceId='+this.deviceId+'&startTime='+this.startTime+'&endTime='+this.endTime;
		this.jsonApiService.http("transportTask/countForTaskV2.html", reqdata).subscribe(data => {
			if(data&&data.data){
				this.allData = data.data[0];
				this.normalData = data.data[1];
				this.abnormalData = data.data[2]
			}
		})
	}
	//初始地图
	initBaiduMap(){
		this.baiduMap= new BMap.Map('baiduMap',{enableMapClick: false}); //创建地图实例
		let point = new BMap.Point(117.7953288,28.2862345); //创建点坐标
		this.baiduMap.centerAndZoom(point, 12); //初始化地图，设置中心点坐标和地图级别
		this.baiduMap.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
	}
	initChart(){
		this.chartOption = {
		    title:{text: '重量曲线',left: 'center',textStyle:{fontSize:15}},
		    tooltip:{
		        trigger: 'axis',
		        axisPointer:{type: 'cross'},
		        formatter: function (params) {
		          	var paramIndex=params[0].dataIndex;
		          	var pointObj=this.trackData[paramIndex];
					if(!pointObj || pointObj.x == '' || pointObj.x == '0') {return};
					this.lineMoveCarPoint(pointObj)
		          	var res='';
		        	var len=params.length;
		        	for(var i=0;i<len;i++){
		        		res=res+params[i].marker+params[i].seriesName+':'+params[i].data+'</br>'
		        	}
		        	return res;
		        }.bind(this)
		    },
		    grid:{left: '48px',right: '36px',top:'60px',bottom:'24px'},
		    toolbox:{show: false},
			legend:{top:'20px'},
		    xAxis:{type: 'category',boundaryGap: false,data:[]},
		    yAxis:[{	
		    		name:'吨',
			        type: 'value',
			        axisLabel: {formatter: '{value}'},
			        axisPointer: {snap: true}
			    },{	
			    	name:'km/h',
		    		splitLine:{show:false},
			        type: 'value',
			        axisLabel: {formatter: '{value}'},
			        axisLine: {lineStyle: {color: '#5793f3'}},
			    }],
		    series: [
		        {
		            name:'重量',
		            type:'line',
		            smooth: true,
		            data:[],
		            markArea: {data: [ [{name: '',xAxis: '' },{xAxis: ''}]]}
		        },{
		            name:'速度',
		            type:'line',
		            smooth: true,
		            yAxisIndex: 1,
					data: [],
					itemStyle: {//样式
						normal: {color: '#5793f3',lineStyle: {width: 1,opacity: 0.5,}}
					},
					areaStyle: {//阴影
		                color: 'rgba(83, 146, 230,0.5)'
		            }
		        }
		    ]
		};
		this.myChart = echarts.init(document.getElementById('myChart'));
		this.myChart .setOption(this.chartOption, true);
		if(this.myChart){
			this.myChart.resize();
		}
		var that=this;
		$(window).resize(function (){
			//当浏览器大小变化时重新计算图表
		    that.myChart.resize();
		});
	}
	colsePop(){
		$('#popPage').animate({'width':0},150);
		this.flag = false;
	}
	isShow(){
		if(!this.flag){
			$('#popPage').animate({'width':"65%",'opacity':1},150);
			$("#popPage").height($(window).height()-60);
			this.flag = true;
		}else{
			$('#popPage').animate({'width':0,'opacity':0},150);
			this.flag = false;
		}
	}
	//初始化基本信息
	initBasInformation(){
		this.basInformation=[ 
			{name:'carNumber',value:'',textStr:'车牌'},
			{name:'dealer',value:'',textStr:'经销商'},
			{name:'goods',value:'',textStr:'货物'},
			{name:'lastLoadWeight',value:'',textStr:'净重'},
			{name:'loadTime',value:'',textStr:'装载耗时'},
			{name:'leaveDate',value:'',textStr:'发车时间'},
			{name:'transportTime',value:'',textStr:'运输时长'},
			{name:'unloadTime',value:'',textStr:'卸载耗时'},
			{name:'unloadEndDate',value:'',textStr:'卸货完成时间'},
			{name:'unloadArea',value:'',textStr:'目的地'},
			{name:'unloadAddress',value:'',textStr:'卸货地址'},
		]
	}
	rowSelectEvent(row){
		this.activeSelected = row.id;
		var rowData=row;
		let timeDelay = 150;//设置动画时间
		if(!rowData.finish){
		    var statuStr='';
		    switch(rowData.status){
	            case 2:
	                statuStr='在途';
	                break;
	            case 3:
	                 statuStr='在场';
	                break;
          	}
	      	this.jsonApiService.message('改车辆处于'+statuStr+'状态,暂不提供数据查询...');
	      	return;
	 	}	
		if(!this.flag){
			$("#popPage").height($(window).height()-60);
			$('#popPage').animate({'width':'65%','opacity':1},timeDelay);
			this.flag = true;
		}
		this.initBasInformation();
		//清空地图轨迹
		clearTrackLine(this.baiduMap);
		this.baiduMap.closeInfoWindow();
		//清空行政区域
		this.baiduMap.removeOverlay(this.areaPly);
		this.baiduMap.removeOverlay(this.carMoveCanvasLayer);
		function nullUpdate() {}
		this.carMoveCanvasLayer = new CanvasLayer({//清空marker圆点
			map: this.baiduMap,
			update: nullUpdate,
			zIndex: 10
		});
		this.baiduMap.addOverlay(this.carMoveCanvasLayer);
		this.mapCantonName=rowData.unloadArea;
		this.mapCarNumber=row.carNumber;
		this.mapDeviceId=rowData.deviceId;
		//画图起始时间进行比较
		var _loadTime=new Date(rowData.loadStartDate).getTime();
		var _enterTime=new Date(rowData.enterDate).getTime();
		if(_loadTime-_enterTime>30*60*1000){
			this.mapStartTime=common.getTimeMmss( new Date(_loadTime-30*60*1000) );
		}else{
			this.mapStartTime=rowData.enterDate;
		}
		this.mapEndTime=rowData.emptyDate;
		if(!this.mapStartTime||!this.mapEndTime){
			this.jsonApiService.message('起始或结束时间不正确...');
			return;
		}
		for (var i=0;i<this.basInformation.length;i++){
			var itemName=this.basInformation[i].name;
			if(itemName === 'lastLoadWeight'){
				this.basInformation[i].value=row[itemName]==null?'--':row[itemName];
			}else{
				this.basInformation[i].value=row[itemName]?row[itemName]:'--';
			}
		}
		if(this.flag){timeDelay = 0}
		this.timeOut = setTimeout(function(){
			this.askforData().then(()=>{
				this.initChart();//初始化折线图
				this.mapDeviceId = '';
				this.drawBoundary();
			});
		}.bind(this),timeDelay);
	}
	askforData(){
		return new Promise(function (resolve, reject) {
			this.trackData=[];
			this.xAxisData=[];
			this.yAxisWeight=[];
			this.yAxisSpeed=[];
			let reqdata = 'deviceId=' + this.mapDeviceId + '&startTime=' + this.mapStartTime + '&endTime=' + this.mapEndTime + '&showModify=' + false;
			this.jsonApiService.http("stats/draw.html", reqdata).subscribe(result => {
				var len = result.data.length;
				if(len<2){
					this.jsonApiService.message('该时间段没有数据...')
					return;
				}
				for(var i=0;i<len;i++){
					var mapPoint=toMapPoint(result.data[i]);
					if(mapPoint){
						this.trackData.push(mapPoint);
					}
					this.xAxisData.push(result.data[i].uploadDate);
					this.yAxisWeight.push(result.data[i].weight);
					this.yAxisSpeed.push(result.data[i].speed);
				}
				resolve();
			})
		}.bind(this))
	}
	//画轨迹图
	drawTrackLine(){
		var geturl=config.BaseURL;
		let lineStyle={star:true,end:false,color:true,infoUrl:geturl};
		drawTrackLine(this.trackData,this.baiduMap,lineStyle);
		
	}
	//绘画行政区域边界
	drawBoundary(){
    	var that=this;
    	if(that.mapCantonName==''||!that.mapCantonName){
    		this.drawChart();
    		this.drawTrackLine();
    		that.baiduMap.removeOverlay(that.areaPly);
    		var centerPoint=new BMap.Point(this.trackData[0].lng, this.trackData[0].lat);
    		that.baiduMap.centerAndZoom(centerPoint, 10);
    		return;
    	}
	    this.boundaryRegion.get(that.mapCantonName, function(rs){       //获取行政区域
	    	that.baiduMap.removeOverlay(that.areaPly);  //清除掉之前的边界区域
	        var count = rs.boundaries.length; //行政区域的点有多少个
	      	that.inRegionTime='';
      		that.outRegionTime='';
	      	if(count<1){
	        	return;
	        }
	        that.areaPly = new BMap.Polygon(rs.boundaries[0], {
	        	strokeColor:'blue',
						fillColor:'red',
						strokeWeight:1,
						strokeOpacity:0.2,
						fillOpacity:0.2
	        }); //建立多边形覆盖物
	        that.baiduMap.addOverlay(that.areaPly);  //添加覆盖物
	        that.baiduMap.setViewport(that.areaPly.getPath());    //调整视野  
	        that.drawTrackLine();
	        that.inTimeArr=[];
     		that.outTimeArr=[];
	     	function getInOutTimeArr(order){
	     		var isOut=false;//判断是否再进入边界后又再次出去
	     		var len=that.trackData.length;
     			for(var i=order;i<len;i++){
	        		var comparePoint=new BMap.Point(that.trackData[i].lng,that.trackData[i].lat);
			    	var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, that.areaPly);
			    	if (result){//在内部，把该点显示在地图上  
				      	that.inTimeArr.push(that.trackData[i].uploadDate);
				      	for(var j=i;j<len;j++){
							var comparePoint=new BMap.Point(that.trackData[j].lng,that.trackData[j].lat);
					    	var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, that.areaPly);
					    	if (!result) {//在内部，把该点显示在地图上  
					    		isOut=true;//判断是否再进入边界后又再次出去
						      	that.outTimeArr.push(that.trackData[j].uploadDate);
						      	if(j<len){
						      		getInOutTimeArr(j);
						      	}
							    break;   
							}
						}
				      	if(!isOut){
				    		that.outTimeArr.push(that.trackData[len-1].uploadDate);
				    	}
					    break;
					}  
	        	}
	     	}
	     	getInOutTimeArr(0);
			that.drawChart();
		})
	}
	//画折线图
	drawChart(){
		this.chartOption.xAxis.data=this.xAxisData;
		this.chartOption.series[0].data=this.yAxisWeight;
		this.chartOption.series[1].data=this.yAxisSpeed;
		var len=this.xAxisData.length;
		if(this.isEnter){
			var timeShadow=[];
			for(var i=0;i<this.inTimeArr.length;i++){
				var dataArr=[{
                    name: '进入特价区域',
                    xAxis: this.inTimeArr[i]
                },{
                	xAxis: this.outTimeArr[i]
           	 	}]
				timeShadow.push(dataArr)
			}
			this.chartOption.series[0].markArea.data= timeShadow;
		}
		this.myChart .setOption(this.chartOption, true);
		//点击折线图  地图展开信息框
//		var that=this;
//		this.myChart.on('click', function(params) {
//			var pointObj= that.trackData[params.dataIndex];
//			if(pointObj == undefined) {
//				return;
//			}
//			
//			var geturl=config.BaseURL;
//			common.createInfoBox(that.baiduMap,pointObj,geturl);
//			
//		})
	}
	//折线移动,地图轨迹添加坐标位置点函数
	lineMoveCarPoint(data) {
		if(data.lat > 0) {
			var mp = this.baiduMap;
			var update = function update() {
				var ctx = this.canvas.getContext("2d");
				if(!ctx) {
					return;
				}
				ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
				var point = new BMap.Point(data.lng, data.lat);
				var pixel = mp.pointToPixel(point);
				ctx.beginPath();
				ctx.strokeStyle = '#d0d4d7';
				ctx.arc(pixel.x, pixel.y, 35, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = 'rgba(35, 152, 255, 0.14)';
				ctx.arc(pixel.x, pixel.y, 34, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.strokeStyle = '#c2c2c4';
				ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = '#fff';
				ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.fillStyle = '#1496ff';
				ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI);
				ctx.fill();
			};
			if(typeof this.carMoveCanvasLayer != 'undefined') {
				this.carMoveCanvasLayer.options.update = update;
				this.carMoveCanvasLayer._draw();
				return;
			}
			this.carMoveCanvasLayer = new CanvasLayer({
				map: this.baiduMap,
				update: update,
				zIndex: 10
			});
		}
	}
	//是否进入特价区域复选框变更事件
	isEnterChange(){
		var len=this.trackData.length;
		
		if(len<2){
			return
		}
		if(this.isEnter){
			var timeShadow=[];
			for(var i=0;i<this.inTimeArr.length;i++){
				var dataArr=[{
                    name: '进入特价区域',
                    xAxis: this.inTimeArr[i]
                },{
                	xAxis: this.outTimeArr[i]
           	 	}]
				timeShadow.push(dataArr)
			}
			this.chartOption.series[0].markArea.data= timeShadow;
		}
		else{
			this.chartOption.series[0].markArea= {
                data: [ [{
                    name: '',
                    xAxis: ''
                },{
                    xAxis: ''
                }]]
            }
			
		}
		this.myChart .setOption(this.chartOption, true);
	}
	//初始化加载list数据
	load(){
		this.activeSelected = '';
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		this.loadSortData();
		var dataType;
		if(this.btnNum === 'all'){
			dataType = '';
		}else if(this.btnNum === 'normal'){
			dataType = '1';
		}else if(this.btnNum === 'abnormal'){
			dataType = '-1';
		}
		let param = {
			"pageSize": this.pageSize,
			"nowPage": this.curPage,
			"parameters": {
				deviceId:this.deviceId,
				startTime:this.startTime,
				endTime:this.endTime,
				status:dataType
			}
		};
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.jsonApiService.http("transportTask/taskListForpageV2.html", reqdata).subscribe(data => {
			if(data&&data.exhibitDatas){
				for(let item of data.exhibitDatas){
					item.weight = common.twoDecimal(item.weight);
					item.loadTime = common.secondToDate(item.loadTime);
					item.unloadTime = common.secondToDate(item.unloadTime);
					item.transportTime = common.secondToDate(item.transportTime);
				}
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}
		})
	}
	//删除所选时间
	del_date(){
		this.startTime = '';
		this.endTime ='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//删除
	deleteRow(row){
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("stats/deletetransportdata.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
}